<?php

/**
 * Subclass for representing a row from the 'uid' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Uid extends BaseUid
{
	public static function getAndValidateUid($requestuid)
	{
		/* @var $uid Uid */
		$c = new Criteria();
		$c->add(UidPeer::UID, $requestuid);
		$uid = UidPeer::doSelectOne($c);
		if(!$uid)
		{
			throw new exceptionNotFound('Uid not found');
		}
		if($uid->getValidTil(null) < time())
		{
			//debugvar(time(), 'time')
			throw new exceptionTimeOut('time out');
		}
		if( $uid->getStatusId() == MyConstants::STATUS_APPROVED)
		{
			return $uid;
		}elseif( $uid->getStatusId() == MyConstants::STATUS_USED )
		{
			throw new exceptionAlreadyUsed('Already used Uid');
		}else 
		{
			throw new exceptionUnexceptedStatus('Unexcepted status!');
		}
	}
	public static function createNew($objId, $objType, $ttl = -1)
	{
		$uid = new self();
		$uid->setUid(md5(mt_rand()));
		$uid->setObjId($objId);
		$uid->setObjType($objType);
		$uid->setStatusId(MyConstants::STATUS_APPROVED);
		//valid two weeks
		if( $ttl == -1 )
		{ 
		     $uid->setValidTil(time() + (60 * 60 * sfConfig::get('app_uid_ttl_hours')));
		}else 
		      $uid->setValidTil(time() + $ttl);
		$uid->save();
		return $uid;
	}
	/**
	 * return new object if not found
	 * @param string $requestuid
	 * @param int $objId
	 * @param int $objType
	 */
	public static function getByUidIdType($requestuid, $objType)
	{
		$c = new Criteria();
        $c->add(UidPeer::UID, $requestuid);
        $c->add(UidPeer::OBJ_TYPE, $objType);
        $uid = UidPeer::doSelectOne($c);
        if ($uid)
        {
        	return $uid;
        }
        else 
        {
        	return new Uid();
        }
	}
	
}
